require 'json'
require 'spoule/json'

module Spoule
  class MediaUpload
    include Spoule::Json

    def initialize(max_size, *mime_types)
      @max_size = max_size
      @mime_types = mime_types.flatten
      
      @protocols = []
    end
    
    def <<(o)
      case o
      when Spoule::MediaUpload::Protocol::Base
        @protocols << o
      else
        raise "Cannot accept objects of type #{o.class}!"
      end
    end

    def to_json(*opts)
      s  = ""
      s += _format_json_prefix('mediaUpload', opts)
      s += _format_json_array('accept', @mime_types, opts)
      s += ',' + _format_json_kvp('maxSize', @max_size, opts)
      s += ',' + _format_json_prefix('protocols', opts)
      s << @protocols.inject([]) {|a,x| a << x.to_json(opts) }.join(',')
      s += _format_json_suffix
      s += _format_json_suffix
    end

    module Protocol
      class Base
        include Spoule::Json

        def initialize(name, path, is_multipart)
          @name = name
          @path = path
          @is_multipart = is_multipart
        end

        def to_json(*opts)
          s  = ""
          s += _format_json_prefix(@name, opts)
          s += _format_json_kvp('path', @path)
          s += ',' + _format_json_kvp('multipart', @is_multipart)
          s += _format_json_suffix
        end
      end

      class Simple < Base
        def initialize(path)
          super('simple', path, true)
        end
      end

      class Resumable < Base
        def initialize(path)
          super('resumable', path, true)
        end
      end
    end
  end
end
